import {
  formatSeconds
} from '../../utils/util.js'

let app = getApp()
Page({
  data: {
    spinShow: false,
    score: 0,
    paperId: null,
    examPaperAnswerId: null,
    form: {},
    timer: null,
    doTime: 0,
    userInfo: null,
    remainTime: 0,
    remainTimeStr: null,
    modalShow: false,
    result: 0,
    timeOutShow: false,
    address: "未打开地理位置授权！",
    latitude: null,
    longitude: null,
    //图片信息
    paper:null,
    pageNew:0,
    //是否是首页
    isFristPage:true,
    //是否是最后一页
    isLastPage:false,
    //是否开始标注
    canBiaoZhu:false,
    //图片id
    imageId:null,
    //错误信息
    errorMsg:null,
    //正确信息
    rightMsg:null,
    //按钮样式以及是否隐藏
    buttonStyle:'',
    display:"",
    //正确个数
    rightNum:0
  },

//标注的实现
handleImageTap(e) {
    console.log(e);
  console.log(this.data.imageId);
  if (this.data.canBiaoZhu) {
    const touch = e.touches[0];
    const x0 = touch.pageX; // 获取触摸点在页面中的水平坐标
    const y0 = touch.pageY; // 获取触摸点在页面中的垂直坐标
    const imageRect = wx.createSelectorQuery().select('.image').boundingClientRect();
    imageRect.exec((rect) => {
      const imageX = rect[0].left; // 获取图片在页面中的水平位置
      const imageY = rect[0].top; // 获取图片在页面中的垂直位置
      const relativeX = x0 - imageX; // 计算触摸点相对于图片左上角的水平坐标
      const relativeY = y0 - imageY; // 计算触摸点相对于图片左上角的垂直坐标
      console.log("触摸点在图片上坐标:", relativeX, relativeY);
      //进行转换  *2  /1.2
      const relativeX1 = relativeX * 2 /1.2;
      const relativeY1 = relativeY * 2 /1.2
      //转换为int
      const relativeX2= parseInt(relativeX1);
      const relativeY2=parseInt(relativeY1);
      console.log("转换到后端坐标:", relativeX2, relativeY2);
      this.setData({
        buttonStyle: `position: absolute; left: ${relativeX-28+10}px; top: ${relativeY-90+40}px;display:block;`, // 设置按钮的样式
      });
      console.log("按钮样式为"+this.data.buttonStyle);
      //开始发送请求
      var token = wx.getStorageSync('token');
      var paperId =wx.getStorageSync('imgExamId');
      wx.request({
        url: 'http://60.216.100.50:9006/ruoyi-api/imgExamination/imgExaminationStu/savetOne',
        method:"POST",
        header: {
          'Authorization': 'Bearer ' + token, // 在请求头中携带 token
          },
        data: {
          id: this.data.imageId,
          paperId:paperId,
          x:relativeX2 ,
          y:relativeY2
        },
        success: (res) => {
          var data = res.data;
          console.log(data); 
          if (data.code==200) {
            wx.showToast({
              title:"您的答案已经标记，请您点击下一页继续答题" ,
              icon: 'none',
              duration: 1000
            });
          }
          //自动跳转下一页
          // setTimeout(() => {
          //   var imgExamNum= wx.getStorageSync('imgExamNum');
          //   if (this.data.pageNew+1<imgExamNum) {
          //     this.nextPage();
          //   }
          // }, 1500);
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
      })
    });
  }
},

//开始标注功能的实现
startDo(){
  this.setData({
    canBiaoZhu:true
  })
  console.log(this.data.canBiaoZhu);
},

//标注完成功能的实现
Docompelte(){
  this.setData({
    canBiaoZhu:false
  })
},

//上一页功能实现
backPage(){
    var token = wx.getStorageSync('token');
    var paperId =wx.getStorageSync('imgExamId');
    var pageNew=this.data.pageNew-1;
    this.setData({
      pageNew:pageNew,
      isLastPage: false, // 设置为第一页
    })
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/system/examinationImg/getOne',
      method:"POST",
      header: {
        'Authorization': 'Bearer ' + token, // 在请求头中携带 token
        },
        data: {
          pageNew: pageNew,
          paperId: paperId
        },
        success: (res) => {
          var data = res.data;
          console.log(data);
          // 处理查询结果
          this.setData({
            paper: data.imgUrl,
            imageId:data.id
          });    
          console.log(this.data.imageId)
          if (pageNew === 0) {
            this.setData({
              isFristPage: true // 设置为第一页
            });
            wx.showToast({
              title: '这已经是首页',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
    })
  },

//下一页功能实现
  nextPage(){
    var token = wx.getStorageSync('token');
    var paperId =wx.getStorageSync('imgExamId');
    var pageNew=this.data.pageNew+1;
    var imgExamNum= wx.getStorageSync('imgExamNum');
    this.setData({
      pageNew:pageNew,
      isFristPage: false,
      rightMsg:null,
      buttonStyle: `display:none;`, // 设置按钮的样式
    })
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/system/examinationImg/getOne',
      method:"POST",
      header: {
        'Authorization': 'Bearer ' + token, // 在请求头中携带 token
        },
        data: {
          pageNew: pageNew,
          paperId: paperId
        },
        success: (res) => {
          var data = res.data;
          console.log(data);
          // 处理查询结果
          this.setData({
            paper: data.imgUrl,
            imageId:data.id
          });    
          console.log("图片id是")
          console.log(this.data.imageId);

          wx.request({
            url: 'http://60.216.100.50:9006/ruoyi-api/imgExamination/imgExaminationStu/selectOne',
            method:"POST",
            header: {
              'Authorization': 'Bearer ' + token, // 在请求头中携带 token
              },
              data: {
                imgId: this.data.imageId,
                paperId: paperId
              },
              success: (res) => {
                console.log(this.data.imageId);
                var data = res.data;
                console.log(data);
                // 处理查询结果
                // this.setData({
                //   paper: data.imgUrl,
                //   imageId:data.id
                // });    
                console.log("第二个请求的数据")
                console.log(this.data.imageId);
                if (pageNew+1>=imgExamNum) {
                  this.setData({
                    isLastPage: true, // 设置为最后一页
                  });
                  wx.showToast({
                    title: '当前是最后一页',
                    icon: 'none',
                    duration: 2000
                  });
                  return;
                }
              },
              fail: function(err) {
                // 处理请求失败
                console.error(err);
              }
          })
          if (pageNew+1>=imgExamNum) {
            this.setData({
              isLastPage: true, // 设置为最后一页
            });
            wx.showToast({
              title: '当前是最后一页',
              icon: 'none',
              duration: 2000
            });
            return;
          }
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
    })
  },

//提交方式
imgExamSubmit(){
    var paperId=  wx.getStorageSync('imgExamId');
    var token = wx.getStorageSync('token');
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/imgExamination/imgExamination/saveScore/'+paperId,
      method:"GET",
      header: {
        'Authorization': 'Bearer ' + token, // 在请求头中携带 token
      },
      // data: {
      //   paperId:paperId,
      //   score1:this.data.rightNum
      // },
      success: function(res) {
        var data = res.data;
        console.log(data);
        if (data.code==200) {
        // 在提交成功后执行其他逻辑
          wx.navigateBack({
            delta: 1, // 返回的页面数，如果是1表示返回上一个页面
          });
        }
      },
      fail: function(err) {
        // 处理请求失败
        console.error(err);
      }
    })
},

//提交表单方法
examSubmit(event) {
  // 处理选择改变事件的逻辑代码
  var paperId = wx.getStorageSync('paperid');
  var siteId = wx.getStorageSync('siteId');
  var token = wx.getStorageSync('token');
  var eoExaminePerson = {
    paperId: paperId,
    siteId: siteId,
  };

  // 弹出确认对话框
  wx.showModal({
    title: '提示',
    content: '确定要提交试卷吗？',
    success: function(res) {
      if (res.confirm) {
        // 用户点击确定，执行提交逻辑
        wx.request({
          url: 'http://60.216.100.50:9006/ruoyi-api/examination/finshExamination',
          method: "POST",
          header: {
            'Authorization': 'Bearer ' + token, // 在请求头中携带 token
          },
          data: eoExaminePerson,
          success: function(res) {
            var data = res.data;
            console.log(data);
            if (data.code==200) {
             // 在提交成功后执行其他逻辑
              wx.navigateBack({
                delta: 1, // 返回的页面数，如果是1表示返回上一个页面
              });
            }
          },
          fail: function(err) {
            // 处理请求失败
            console.error(err);
          }
        });
      } else if (res.cancel) {
        // 用户点击取消，继续答题逻辑
        console.log('用户取消提交，继续答题');
        // 执行其他继续答题的逻辑
      }
    }
  });
},

  onShow: function () {

  },

//页面初始化：界面
  onLoad: function (options) {
    var data = JSON.parse(decodeURIComponent(options.data)); // 解析传递的试题数据
    console.log(data);
    this.setData({
      paper: data.imgUrl, // 将试题数据设置到页面的data中
      imageId:data.id
    });
    console.log(this.data.imageId)
    var token = wx.getStorageSync('token');
    var paperId =wx.getStorageSync('imgExamId');
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/imgExamination/imgExaminationStu/selectOne',
      method:"POST",
      header: {
        'Authorization': 'Bearer ' + token, // 在请求头中携带 token
        },
        data: {
          imgId: this.data.imageId,
          paperId: paperId
        },
        success: (res) => {
          var data = res.data;
          console.log(data);  
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
    })

    wx.enableAlertBeforeUnload({
      message: '确认退出考试？退出考试将自动提交试卷！',
      success: res => {
        wx.vibrateShort({
          type: 'heavy'
        })
      },
      fail: err => {}
    });

    wx.onUserCaptureScreen(function (res) {
      wx.showModal({
        title: '提示',
        content: '严禁截屏，如有下次，自动提交试卷！'
      })
    });
  },


  onUnload() {
    clearInterval(this.data.timer)
  },

  returnRecord() {
    // wx.reLaunch({
    //   url: '/pages/record/index',
    // });
    app.globalData.examPaperAnswerId = this.data.examPaperAnswerId,
      // app.globalData.userScore =  this.data.score,
      console.log("我要传输的ID是" + this.data.examPaperAnswerId),
      wx.navigateTo({
        url: '/packageF/exam/result/index?id=' + app.globalData.examPaperAnswerId,
      })
  },

  formSubmit: function (e) {
    let _this = this
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    e.detail.value.id = this.data.paperId
    e.detail.value.doTime = this.data.doTime
    e.detail.value.address = this.data.address
    e.detail.value.latitude = this.data.latitude
    e.detail.value.longitude = this.data.longitude
    let title = this.data.form.name
    app.formPost('/api/wx/student/exampaper/answer/answerSubmit', e.detail.value)
      .then(res => {
        if (res.code === 1) {
          _this.setData({
            modalShow: true,
            result: res.response.score,
            examPaperAnswerId: res.response.examPaperAnswerId
          });
          app.globalData.userScore = res.response.score
          let fenshu = res.response.score;
          console.log(fenshu);
          let userName = _this.data.userInfo.realName;
          console.log(userName);
          let paperScore = (_this.data.score * 0.6).toFixed();
          console.log(paperScore);
          let address = _this.data.address
          console.log(address)
          wx.cloud.callFunction({
            name: 'getOpenId'
          }).then(res => {
            console.log(res);
            let openid = res.result.openid
            console.log("获取openid成功！", openid)
            wx.cloud.callFunction({
              config: {
                env: 'dabenben-jrvrn'
              },
              // 要调用的云函数名称
              name: 'sendNewMsg',
              // 传递给云函数的参数
              data: {
                openid: openid,
                // theme:"本次考试"+jige+",有问题联系陈鹏！",
                theme: address,
                number: fenshu,
                title: title,
                username: userName,
                bukao: "本次考试及格分：" + paperScore + "分"
              },
              success: res => {
                console.log(res)
              },
              fail: err => {
                console.log(err)
              },
            })
          })
          wx.vibrateShort({
            type: 'medium'
          })
        } else {
          app.message(res.response, 'error')
        }
        wx.hideLoading()
      }).catch(e => {
        wx.hideLoading()
        app.message(e, 'error')
      })
  }
})